package com.mishow.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.mishow.R;
import com.mishow.activity.base.BaseActivity;
import com.mishow.adapter.PersonalDynamicRecyclerAdapter;
import com.mishow.adapter.PersonalSelectRecyclerAdapter;
import com.mishow.bean.RedsBean;
import com.mishow.log.MyLog;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.request.core.Response;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.UserCenterInfoResponse;
import com.mishow.request.response.UserCenterInfoResponse.Result;
import com.mishow.request.result.Stature;
import com.mishow.request.result.User;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.DeviceUtil;
import com.mishow.utils.StringUtil;
import com.mishow.utils.ToastUtil;
import com.mishow.utils.ImageLoader.ImageLoaderProxy;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.widget.CirculatoryViewPager;
import com.mishow.widget.DividerItemDecoration;
import com.mishow.widget.FullyLinearLayoutManager;
import com.mishow.widget.MyRecycleView;
import com.mishow.widget.PullToZoomListView;
import com.mishow.widget.share.ShareDialog;
import com.mishow.widget.share.ShareUtil.ShareListener;
import com.mishow.widget.share.ShareView;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
/**
 * 作者：wei.miao<br/>
 * 描述：个人主页
 */
public class PersonalMainActivity extends BaseActivity{
	
	private PullToZoomListView listView;
	private String[] adapterData; 
	
	private SharedPreferencesUtil mShPreferencesUtil;
	
	private RelativeLayout relatie_start_info;
	private ImageView image_personal_head;
	/** 用户昵称 **/
	private TextView text_user_cname;
	/** 个人签名 **/
	private TextView text_user_graph;
	/** 用户省份 **/
	private TextView text_user_location;
	
	/** 粉丝数 **/
	private TextView texdt_user_fans;
	/** 关注数 **/
	private TextView texdt_user_guan;
	
	/** 身高 **/
	private TextView text_user_height;
	/** 体重 **/
	private TextView text_user_weight;
	/** 三围 **/
	private TextView text_user_sanwei;
	/** 脚码 **/
	private TextView text_user_feet;
	
	private ImageView image_back;
	/** 模特资料图片 **/
	private CirculatoryViewPager cvp_mode_photo;
	/** 精选图片 **/
	private MyRecycleView recyclerview_select;
	/** 动态图片 **/
	private MyRecycleView recyclerview_dynamic;
	
	/** 风格标签 **/
	private TextView text_user_stylelable;
	/** 外貌标签 **/
	private TextView text_user_earancelabel;
	/** 体型标签 **/
	private TextView text_user_shapelabel;
	/** 魅力部位标签 **/
	private TextView text_user_charmlabel;
	
	/** 个人动态更多 **/
	private TextView text_dynamic_more;
	
	/** 个人精选更多 **/
	private TextView text_select_more;
	/** 直接联系 **/
	private TextView txt_user_contact;
	/** 关注 **/
	private TextView txt_user_concern;
	/** 分享 **/
	private ImageView image_share;
	/** **/
	private PersonalSelectRecyclerAdapter selectRecyclerAdapter;
	
	private PersonalDynamicRecyclerAdapter dynamicRecyclerAdapter;
	/** 精选 **/
	private ArrayList<String> mPiclist;
	/** 个人动态 **/
	private ArrayList<String> mChats;
	
	/** banner图片 **/
	private ArrayList<String> bannerPics;
	
	private FullyLinearLayoutManager linearLayoutManager;
	
	private LinearLayoutManager layoutManager;
	
	private String userId;
	
	private String userName;
	
	public static void intoActivity(Context context) {

		Intent intent = new Intent(context, PersonalMainActivity.class);
		context.startActivity(intent);

	}
	@Override
	protected void initData() {
		
		bannerPics = new ArrayList<String>();
		
		linearLayoutManager = new FullyLinearLayoutManager(mContext);
		layoutManager = new LinearLayoutManager(mContext);
		//----------------------------------------------
		bannerPics.add("http://www.xxjxsj.cn/article/uploadpic/2012-5/201251221048859.jpg");
		bannerPics.add("http://www.pptbz.com/pptpic/UploadFiles_6909/201406/2014061007022710.jpg");
		bannerPics.add("http://www.xxjxsj.cn/article/uploadpic/2012-5/201251221048859.jpg");
		bannerPics.add("http://www.pptbz.com/pptpic/UploadFiles_6909/201406/2014061007022710.jpg");
		//-----------------------------------------------
		mPiclist = new ArrayList<String>();
		
		mChats = new ArrayList<String>();
		selectRecyclerAdapter = new PersonalSelectRecyclerAdapter(mContext, mPiclist);
		
		dynamicRecyclerAdapter = new PersonalDynamicRecyclerAdapter(mContext, mChats);
		
		mShPreferencesUtil = new SharedPreferencesUtil(mContext);
	}

	@Override
	protected void initView(Bundle savedInstanceState) {
		
		setContentView(R.layout.activity_personal_main);
		listView = (PullToZoomListView)findViewById(R.id.listview);
		
		relatie_start_info =  (RelativeLayout)findViewById(R.id.relatie_start_info);
		image_personal_head = (ImageView)findViewById(R.id.image_personal_head);
		
		text_user_cname = (TextView)findViewById(R.id.text_user_cname);
		text_user_graph = (TextView)findViewById(R.id.text_user_graph);
		text_user_location = (TextView)findViewById(R.id.text_user_location);
		
		
		texdt_user_fans = (TextView)findViewById(R.id.texdt_user_fans);
		texdt_user_guan = (TextView)findViewById(R.id.texdt_user_guan);
		
		text_user_height = (TextView)findViewById(R.id.text_user_height);
		text_user_weight = (TextView)findViewById(R.id.text_user_weight);
		text_user_sanwei = (TextView)findViewById(R.id.text_user_sanwei);
		text_user_feet = (TextView)findViewById(R.id.text_user_feet);
		
		
		text_user_stylelable = (TextView)findViewById(R.id.text_user_stylelable);
		text_user_earancelabel = (TextView)findViewById(R.id.text_user_earancelabel);
		text_user_shapelabel = (TextView)findViewById(R.id.text_user_shapelabel);
		text_user_charmlabel = (TextView)findViewById(R.id.text_user_charmlabel);
		
		image_back = (ImageView)findViewById(R.id.image_back);
		
		cvp_mode_photo = (CirculatoryViewPager)findViewById(R.id.cvp_mode_photo);
		
		recyclerview_select = (MyRecycleView)findViewById(R.id.recyclerview_select);
		
		recyclerview_dynamic = (MyRecycleView)findViewById(R.id.recyclerview_dynamic);
		
		text_dynamic_more = (TextView)findViewById(R.id.text_dynamic_more);
		
		text_select_more = (TextView)findViewById(R.id.text_select_more);
		
		
		txt_user_contact = (TextView)findViewById(R.id.txt_user_contact);
		txt_user_concern = (TextView)findViewById(R.id.txt_user_concern);
		
		image_share = (ImageView)findViewById(R.id.image_share);
	}

	
	@SuppressLint("NewApi")
	@Override
	protected void setAttribute() {

		adapterData = new String[] { "Activity", "Service", "Content Provider",
				"Intent", "BroadcastReceiver", "ADT", "Sqlite3", "HttpClient",
				"DDMS", "Android Studio", "Fragment", "Loader" };

		listView.setAdapter(new ArrayAdapter<String>(PersonalMainActivity.this,
				android.R.layout.simple_list_item_1, adapterData));
		listView.getHeaderView().setImageResource(R.drawable.icon_person);
		listView.getHeaderView().setScaleType(ScaleType.CENTER_CROP);
		
		
		image_back.setOnClickListener(clickListener);
		
		LayoutParams bannerLp = cvp_mode_photo.getLayoutParams();
		bannerLp.height = DeviceUtil.dip2px(mContext, 193);
		cvp_mode_photo.setData(bannerPics);
		
		
		//设置布局管理器 
		//最后一个参数表示是否反向布局/数据是从右向左布局的，这就是逆向布局
		recyclerview_select.setLayoutManager(new FullyLinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
		recyclerview_select.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.HORIZONTAL_LIST));
		recyclerview_select.setAdapter(selectRecyclerAdapter);
		
		
		//设置布局管理器  
		recyclerview_dynamic.setLayoutManager(new FullyLinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
		recyclerview_dynamic.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.HORIZONTAL_LIST));
		recyclerview_dynamic.setAdapter(dynamicRecyclerAdapter);
		
		text_dynamic_more.setOnClickListener(clickListener);
		text_select_more.setOnClickListener(clickListener);
		txt_user_contact.setOnClickListener(clickListener);
		txt_user_concern.setOnClickListener(clickListener);
		image_share.setOnClickListener(clickListener);
		
		getUserCenterFromApi();
		
	}

	
	/** 当前屏幕密度 **/
	private float density;
	/**
	 * 下载主页头像封面图片
	 * 
	 * @param url
	 *            下载图片地址
	 */
	private void downLoadImage(String url) {
		density = DeviceUtil.getDeviceDisplayDensity(this);
	    MyLog.d ("density" + density);
		LayoutParams param = (LayoutParams) relatie_start_info.getLayoutParams();
		if (density == 0.75f) {

			param.height = DeviceUtil.dip2px(mContext, 158);

		} else if (density == 1.0f || density == 1.5f) {

			param.height = DeviceUtil.dip2px(mContext, 210);

		} else if (density == 2.0f) {

			param.height = DeviceUtil.dip2px(mContext, 250);

		} else {

			param.height = DeviceUtil.dip2px(mContext, 250);
		}
		if (!TextUtils.isEmpty(url)) {

			ImageLoaderProxy.getInstance(mContext).displayImage(url, image_personal_head, R.drawable.mph_drug_default);
		}
	}
	
	private OnClickListener clickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.image_back:
				finish();
				break;
			case R.id.text_select_more:
				ToastUtil.show(mContext, "精选更多");
				MySelectActivity.intoActivity(mContext);
				break;
			case R.id.text_dynamic_more://个人动态更多
				MyStarDynamicActivity.intoActivity(mContext);
				break;
			case R.id.txt_user_contact://直接联系
				if (userName != null && !userName.equals("")) {
					ChatMishowActivity.intoActivity(mContext,userId,userName);
				}else{
					ToastUtil.show(mContext, "用户不存在");
				}
				break;
			case R.id.txt_user_concern://关注
				if (!userId.equals("0")) {
					doFocus(userId);
				}else{
					ToastUtil.show(mContext, "用户不存在");
				}
				break;
			case R.id.image_share:
				share();
				break;
			default:
				break;
			}
		}
	};
	
	
	/**
	 * 获取个人中心数据
	 */
	private void getUserCenterFromApi() {

		if (!AndroidUtil.isNetworkAvailable(mContext)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("userId", mShPreferencesUtil.getUserId());//用户ID
		
		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(mContext,
				HttpUrlConstant.GET_USER_CENTER);
		OnResponseListener<UserCenterInfoResponse> listener = new OnResponseListener<UserCenterInfoResponse>(mContext) {

			@Override
			public void onSuccess(UserCenterInfoResponse response) {

				Result result = response.getBody().getResult();
				if (result != null) {

					setDisplayData(result);
				}
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {
				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<UserCenterInfoResponse>(
				Request.Method.POST, postUrl, UserCenterInfoResponse.class,
				listener, listener).setParams(lastParams));
	}
	
	/**
	 * 处理返回数据
	 * @param result 返回数据
	 */
	private void setDisplayData(Result result){
		//用户数据 
		User user = result.getUser();
		downLoadImage(user.getUserTopImg());
		text_user_cname.setText(user.getUserCname());
		userId = user.getUserId()+"";
		userName = user.getUserCname();
		if(user.getUserCity()!= null && !user.getUserCity().equals("")){
			text_user_location.setText(user.getUserCity());
		}else{
			text_user_location.setVisibility(View.GONE);
		}
		
		if(user.getUserAccount() != null && !user.getUserAutograph().equals("")){
			text_user_graph.setText(user.getUserAccount());
		}else{
			text_user_graph.setText("这个人很懒，什么都没有留下");
		}
		
		//(模特)丽质资料
		Stature stature = result.getStature();
		text_user_height.setText(stature.getStatureHeight()+"");
		text_user_weight.setText(stature.getStatureWeight()+"");
		text_user_sanwei.setText(stature.getStatureMeasurements()+"");
		text_user_feet.setText(stature.getStatureFeet()+"");
		//精选
		ArrayList<String> piclist = result.getPiclist();
		if (piclist != null && mPiclist.size() > 0) {
			mPiclist.addAll(piclist);
		}
		//个人动态
		ArrayList<String> chats = result.getChats();
		if (chats != null && mChats.size() > 0) {
			mChats.addAll(chats);
		}
		//风格标签
		String stylelabel = StringUtil.replaceString(result.getStylelabel());
		text_user_stylelable.setText(Html.fromHtml(String.format(mContext.getString(R.string.str_user_stylelable), stylelabel)));
		//外貌标签
		String earancelabel = StringUtil.replaceString(result.getEarancelabel());
		text_user_earancelabel.setText(Html.fromHtml(String.format(mContext.getString(R.string.str_user_earancelabel), earancelabel)));
		//体型标签
		String shapelabel = StringUtil.replaceString(result.getShapelabel());
		text_user_shapelabel.setText(Html.fromHtml(String.format(mContext.getString(R.string.str_user_shapelabel), shapelabel)));
		//魅力部位
		String charmlabel = StringUtil.replaceString(result.getCharmlabel());
		text_user_charmlabel.setText(Html.fromHtml(String.format(mContext.getString(R.string.str_user_charmlabel), charmlabel)));
		
	}
	/**
	 * 关注
	 */
	private void doFocus(String userId){
		
		if (!AndroidUtil.isNetworkAvailable(mContext)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("concernId", userId);//关注ID
		params.put("concernUserId", mShPreferencesUtil.getUserId());

		Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(mContext,HttpUrlConstant.SAVE_CONCERN);
		OnResponseListener<Response> listener = new OnResponseListener<Response>(mContext) {

			@Override
			public void onSuccess(Response response) {
				ToastUtil.show(mContext, response.getBody().getMessage());
			}

			@Override
			public void onError(String code, String message) {
				ToastUtil.show(mContext, message);
			}
			@Override
			public void onCompleted() {
				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<Response>(
				Request.Method.POST, postUrl, Response.class,
				listener, listener).setParams(lastParams));
		
	}
	
	private ShareDialog shareDialog;// 分享对话框

	/**
	 * 显示分享对话框
	 */
	private void share() {
		if (shareDialog == null) {
			shareDialog = new ShareDialog(this, ShareView.TYPE_SHARE_APP);
			shareDialog.setShareContent("title", "content", "http://www.baidu.com", "http://pic74.nipic.com/file/20150806/20968868_172407221000_2.jpg");
			shareDialog.setShareListener(new ShareListener() {
				
				@Override
				public void shareCallBack(SHARE_MEDIA platform, int result, String message) {
					
					ToastUtil.show(mContext, message);
				}
			});
		}
		shareDialog.show();
	}
	/**
	 * 最后在分享所在的Activity里复写onActivityResult方法,注意不可在fragment中实现，如果在fragment中调用分享，
	 * 在fragment依赖的Activity中实现，如果不实现onActivityResult方法，会导致分享或回调无法正常进行
	 */
	@Override
	  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	        super.onActivityResult(requestCode, resultCode, data);
	        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

	    }
}
